<template>
  <div class="container">
    <div class="top">
      <header class="mask-paper">
        <div class="brand-container">
          <div class="logo-animation">
            <div class="logo-icon">
              <div class="logo-square"></div>
              <div class="logo-circle"></div>
            </div>
          </div>
          <div class="logo-text">
            路趣智行
            <span class="logo-subtitle">LUKI AI</span>
          </div>
        </div>
        <div class="tool-box"></div>
        <div class="input-box">
          <input 
            type="text" 
            class="search-input" 
            :placeholder="searchPlaceholder" 
            v-model="searchKeyword"
            @keyup.enter="handleSearch"
          />
          <div class="input-button">
            <div class="close-icon" v-if="searchKeyword" @click="clearSearch">
              <Close style="width: 1em; height: 1em; margin-right: 8px" />
            </div>
            <div class="search-icon" @click="handleSearch">
              <Search style="width: 1em; height: 1em; margin-right: 8px" />
            </div>
          </div>
          <button class="ai-recognition-text-btn" @click="openAIRecognition">
            <Camera style="width: 1em; height: 1em; margin-right: 4px" />
            AI智能识图
          </button>
        </div>

        <div class="right">
          <button v-if="!isLoggedIn" class="login-button" @click="showLoginModal">登录</button>
          <button class="right" @click="handleCreationCenter">创作中心</button>
        </div>
      </header>
    </div>
    <div class="main">
      <div class="side-bar">
        <ul class="channel-list">
          <li :class="{ 'active-channel': isActiveRoute('/dashboard') }" @click="toDashboard">
            <div class="link-wrapper">
              <House style="width: 1.5em; height: 1.5em" />
              <span class="channel">首页</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/map') }" @click="toMap">
            <div class="link-wrapper">
              <MapLocation style="width: 1.5em; height: 1.5em" />
              <span class="channel">地图</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/followTrend') }" @click="toTrend">
            <div class="link-wrapper">
              <Star style="width: 1.5em; height: 1.5em" />
              <span class="channel">关注</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/secondhand') || route.path.startsWith('/secondhand/') }" @click="toSecondHand">
            <div class="link-wrapper">
              <Goods style="width: 1.5em; height: 1.5em" />
              <span class="channel">二手</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/message') || isActiveRoute('/agreeCollection') || isActiveRoute('/follower') || isActiveRoute('/comment') || isActiveRoute('/chat') }" @click="toMessage">
            <div class="link-wrapper">
              <Bell style="width: 1.5em; height: 1.5em" />
              <span class="channel">消息</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/push') || isActiveRoute('/push/note') || isActiveRoute('/push/disaster') || isActiveRoute('/push/secondhand') }" @click="toPush">
            <div class="link-wrapper">
              <CirclePlus style="width: 1.5em; height: 1.5em" />
              <span class="channel">发布</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/publicity') }" @click="toPublicity">
            <div class="link-wrapper">
              <ArrowRight style="width: 1.5em; height: 1.5em" />
              <span class="channel">宣传页</span>
            </div>
          </li>
          <li :class="{ 'active-channel': isActiveRoute('/user') || isActiveRoute('/user/note') || isActiveRoute('/user/collection') || isActiveRoute('/user/order') || isActiveRoute('/user/useraddrs') }" @click="toUser">
            <div class="link-wrapper">
              <User style="width: 1.5em; height: 1.5em" />
              <span class="channel">个人</span>
            </div>
          </li>
        </ul>


        <div class="information-wrapper" @click="toggleInfoPanel">
          <More style="width: 1em; height: 1em; margin-right: 8px" /> <span class="channel"> 更多</span>
        </div>

        <div v-if="showInfoPanel" class="information-container">
          <div class="information-pad">
            <div class="container">
              <div>
                <div>
                  <div class="group-wrapper">
                    <div class="menu-item hover-effect" @click="toPublicity">
                      <span>关于路趣智行</span>
                      <div class="icon">
                        <ArrowRight style="width: 1em; height: 1em; margin-right: 8px" />
                      </div>
                    </div>
                  </div>
                  <div class="divider"></div>
                </div>
                <div>
                  <div class="group-wrapper">
                    <div class="group-header">设置</div>
                    <div class="menu-item hover-effect" v-if="isLoggedIn" @click="handleLogout">
                      <span>退出登录</span>
                    </div>
                    <div class="menu-item hover-effect" v-else @click="showLoginModal">
                      <span>登录/注册</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-content with-side-bar">
        <router-view />
      </div>
    </div>

    <!-- AI识别对话框 -->
    <AIRecognitionDialog v-if="showAIRecognition" @close="closeAIRecognition" />
  </div>
</template>

<script lang="ts" setup>
import {
  Search,
  Sunny,
  Moon,
  Close,
  House,
  Star,
  Bell,
  User,
  ArrowRight,
  More,
  CirclePlus,
  Goods,
  Camera,
  MapLocation,
} from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted, onUnmounted, computed, getCurrentInstance, watch } from "vue";
import UserUtil from "@/utils/User/User";
import AIRecognitionDialog from "@/pages/AIrecognition/AIRecognitionDialog.vue";
import { LoginService } from "@/utils/loginService";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 用户信息相关
const userInfo = ref(null);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
const isLoggedIn = computed(() => UserUtil.isLogin());

// UI状态
const showInfoPanel = ref(false);
const searchKeyword = ref('');
const showAIRecognition = ref(false);

// 搜索相关 - 新增
const searchPlaceholder = computed(() => {
  // 根据当前路由判断搜索类型
  if (route.path.startsWith('/secondhand')) {
    return '搜索二手商品';
  } else {
    return '搜索游记';
  }
});

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    if (isLoggedIn.value) {
      const info = await UserUtil.getUserInfo();
      if (info) {
        userInfo.value = info;
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 显示登录弹窗
const showLoginModal = async () => {
  try {
    const { success, userData } = await proxy.$login.show();
    if (success) {
      ElMessage.success('登录成功');
      await fetchUserInfo();
    }
  } catch (error) {
    console.error('登录过程中发生错误:', error);
  }
};

// 退出登录
const handleLogout = async () => {
  try {
    await UserUtil.logout();
    ElMessage.success('已退出登录');
    userInfo.value = null;
    showInfoPanel.value = false;
    router.go(0)
  } catch (error) {
    console.error('退出登录失败:', error);
    ElMessage.error('退出登录失败');
  }
};

// 判断当前路由是否匹配给定的路径
const isActiveRoute = (path: string) => {
  // 精确匹配路径
  if (route.path === path) return true;
  
  // 对于个人页面的子路由匹配
  if (path === '/user' && route.path.startsWith('/user/')) return true;
  
  // 对于发布页面的子路由匹配
  if (path === '/push' && route.path.startsWith('/push/')) return true;
  
  // 对于创作中心的子路由匹配
  if (path === '/platform' && route.path.startsWith('/platform/')) return true;
  
  // 对于二手市场的子路由匹配
  if (path === '/secondhand' && route.path.startsWith('/secondhand/')) return true;
  
  // 对于消息页面的子路由匹配
  if (path === '/message' && 
     (route.path === '/agreeCollection' || 
      route.path === '/follower' || 
      route.path === '/comment' || 
      route.path === '/chat')) return true;
  
  return false;
};

// 切换信息面板显示状态
const toggleInfoPanel = (event: Event) => {
  event.stopPropagation(); // 阻止事件冒泡
  showInfoPanel.value = !showInfoPanel.value;
};

// 点击其他地方关闭信息面板
const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement;
  const infoContainer = document.querySelector('.information-container');
  const infoWrapper = document.querySelector('.information-wrapper');

  if (showInfoPanel.value &&
      infoContainer &&
      !infoContainer.contains(target) &&
      infoWrapper &&
      !infoWrapper.contains(target)) {
    showInfoPanel.value = false;
  }
};

// 组件挂载时添加全局点击事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
  fetchUserInfo();
});

// 组件卸载时移除全局点击事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 路由跳转方法保持不变
const toDashboard = () => {
  router.push({ path: "/dashboard" });
};

const toMap = () => {
  router.push({ path: "/map" });
}

const toTrend = () => {
  router.push({ path: "/followTrend" });
};

const toMessage = () => {
  router.push({ path: "/message" });
};

const toUser = () => {
  router.push({ path: "/user" });
};

const toPush = () => {
  router.push({ path: "/push" });
};

const toCreationCenter = () => {
  router.push({ path: "/platform" });
};

const toSecondHand = () => {
  router.push('/secondhand');
};

// 处理搜索 - 修改
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    if (route.path.startsWith('/secondhand')) {
      // 搜索二手商品
      router.push({
        path: '/secondhand/search',
        query: { 
          keyword: searchKeyword.value,
        }
      });
    } else {
      // 搜索游记
      router.push({
        path: '/search',
        query: { keyword: searchKeyword.value }
      });
    }
  }
};

const clearSearch = () => {
  searchKeyword.value = '';
};

// AI识别页面跳转
const openAIRecognition = () => {
  // showAIRecognition.value = true;
  router.push({
    path: '/aiRecognition',
  });
};

const closeAIRecognition = () => {
  showAIRecognition.value = false;
};

// 添加跳转到 publicity 页面的方法
const toPublicity = () => {
  router.push({ path: "/publicity" });
  showInfoPanel.value = false; // 关闭菜单面板
};

// 添加创作中心点击处理函数
const handleCreationCenter = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录后再访问创作中心');
    return;
  }
  toCreationCenter();
};
</script>

<style lang="less" scoped>
.container {
  max-width: 1728px;
  background-color: #fff;
  margin: 0 auto;

  .top {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100vw;
    height: 72px;
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;
    align-items: center;
    background: #fff;

    header {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      max-width: 1728px;
      height: 72px;
      padding: 0 16px 0 8px;
      z-index: 10;

      .tool-box {
        width: 24px;
        height: 70px;
        position: absolute;
        left: 0;
        top: 0;
      }

      .input-box {
        height: 40px;
        position: fixed;
        left: 50%;
        transform: translate(-50%);
        display: flex;


        @media screen and (max-width: 695px) {
          display: none;
        }

        @media screen and (min-width: 960px) and (max-width: 1191px) {
          width: calc(-36px + 50vw);
        }

        @media screen and (min-width: 1192px) and (max-width: 1423px) {
          width: calc(-33.6px + 40vw);
        }

        @media screen and (min-width: 1424px) and (max-width: 1727px) {
          width: calc(-42.66667px + 33.33333vw);
        }

        @media screen and (min-width: 1728px) {
          width: 533.33333px;
        }
        .search-input {
          padding: 0 84px 0 16px;
          width: 100%;
          height: 100%;
          font-size: 16px;
          line-height: 120%;
          color: #333;
          caret-color: #ff2442;
          background: rgba(0, 0, 0, 0.03);
          border-radius: 999px;
        }

        .input-button {
          position: absolute;
          right: 0;
          top: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100%;
          color: rgba(51, 51, 51, 0.8);

          .close-icon .search-icon {
            width: 40px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            color: rgba(51, 51, 51, 0.8);
          }
        }
      }
    }
  }

  .main {
    display: flex;

    .side-bar {
      @media screen and (max-width: 695px) {
        display: none;
      }
      @media screen and (min-width: 696px) and (max-width: 959px) {
        display: none;
      }

      @media screen and (min-width: 960px) and (max-width: 1191px) {
        width: calc(-18px + 25vw);
        margin-left: 12px;
      }

      @media screen and (min-width: 1192px) and (max-width: 1423px) {
        width: calc(-16.8px + 20vw);
        margin-left: 12px;
      }

      @media screen and (min-width: 1424px) and (max-width: 1727px) {
        width: calc(-21.33333px + 16.66667vw);
        margin-left: 16px;
      }

      @media screen and (min-width: 1728px) {
        width: 266.66667px;
        margin-left: 16px;
      }
      z-index: 10;

      height: calc(100vh - 72px);
      background-color: #fff;
      display: flex;
      flex-direction: column;
      flex-shrink: 0;
      justify-content: space-between;
      padding: 16px 0;
      margin-top: 72px;
      position: fixed;
      overflow: visible;

      .channel-list {
        min-height: auto;
        -webkit-user-select: none;
        user-select: none;

        .active-channel {
          background-color: rgba(0, 0, 0, 0.03);
          border-radius: 999px;
          color: #333;
        }

        li {
          padding-left: 16px;
          min-height: 48px;
          display: flex;
          align-items: center;
          cursor: pointer;
          margin-bottom: 8px;
          color: rgba(51, 51, 51, 0.6);

          .link-wrapper {
            display: flex;
            width: 100%;
            height: 48px;
            align-items: center;
          }
        }

        .channel {
          font-size: 16px;
          font-weight: 600;
          margin-left: 12px;
          color: #333;
        }
      }

      .information-wrapper {
        user-select: none;
        display: flex;
        align-items: center;
        padding-left: 16px;
        min-height: 48px;
        cursor: pointer;
        margin-top: 8px;
        color: rgba(51, 51, 51, 0.6);

        &:hover {
          background-color: rgba(0, 0, 0, 0.03);
          border-radius: 999px;
        }
      }

      .information-container {
        position: absolute;
        bottom: 60px;
        left: 0;
        width: 100%;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        z-index: 100;

        .information-pad {
          padding: 16px;

          .container {
            .group-wrapper {
              margin-bottom: 16px;

              .group-header {
                font-size: 14px;
                font-weight: 600;
                color: #333;
                margin-bottom: 8px;
              }

              .menu-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 12px 8px;
                border-radius: 8px;
                cursor: pointer;

                &.hover-effect:hover {
                  background-color: rgba(0, 0, 0, 0.03);
                }

                span {
                  font-size: 14px;
                  color: #333;
                }

                .multistage-toggle {
                  display: flex;
                  background-color: rgba(0, 0, 0, 0.06);
                  border-radius: 999px;
                  padding: 2px;

                  .toggle-item {
                    width: 28px;
                    height: 28px;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: transparent;
                    border: none;
                    cursor: pointer;

                    &.active {
                      background-color: #fff;
                      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                    }

                    .icon-wrapper {
                      color: #333;
                    }
                  }
                }
              }
            }

            .divider {
              height: 1px;
              background-color: rgba(0, 0, 0, 0.06);
              margin: 8px 0;
            }
          }
        }
      }
    }

    .main-content {
      flex: 1;
      margin-top: 72px;
      min-height: calc(100vh - 72px);

      &.with-side-bar {
        @media screen and (max-width: 695px) {
          margin-left: 0;
        }
        @media screen and (min-width: 696px) and (max-width: 959px) {
          margin-left: 0;
        }

        @media screen and (min-width: 960px) and (max-width: 1191px) {
          margin-left: calc(-18px + 25vw);
        }

        @media screen and (min-width: 1192px) and (max-width: 1423px) {
          margin-left: calc(-16.8px + 20vw);
        }

        @media screen and (min-width: 1424px) and (max-width: 1727px) {
          margin-left: calc(-21.33333px + 16.66667vw);
        }

        @media screen and (min-width: 1728px) {
          margin-left: 266.66667px;
        }
      }
    }
  }
}

// 更新AI识别按钮样式为红紫渐变文字按钮
.ai-recognition-text-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  border: none;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  margin-right: 12px;
  position: absolute;
  top: 2px;
  right: -130px;
  
  // 渐变文字效果
  background: linear-gradient(90deg, #ff2442 0%, #7e1bcc 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  
  // 图标颜色匹配
  :deep(svg) {
    color: #ff2442;
  }
  
  // 悬停效果
  &:hover {
    opacity: 0.8;
    
    &::after {
      transform: scaleX(1);
    }
  }
  
  // 底部渐变线条
  &::after {
    content: '';
    position: absolute;
    bottom: 4px;
    left: 16px;
    right: 16px;
    height: 2px;
    background: linear-gradient(90deg, #ff2442 0%, #7e1bcc 100%);
    transform: scaleX(0);
    transform-origin: left;
    transition: transform 0.3s ease;
  }
}

/* 添加登录按钮样式 */
.login-button {
  padding: 8px 20px;
  background: linear-gradient(90deg, #ff2442 0%, #ff416c 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  margin-right: 16px;
  transition: all 0.3s ease;
  
  &:hover {
    opacity: 0.9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 36, 66, 0.2);
  }
}

/* 添加创作中心按钮样式 */
.right {
  display: flex;
  align-items: center;
}

.right button {
  padding: 8px 20px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.right button.right {
  background-color: rgba(255, 36, 66, 0.1);
  color: #ff2442;
  border: 1px solid rgba(255, 36, 66, 0.3);
  
  &:hover {
    background-color: rgba(255, 36, 66, 0.15);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 36, 66, 0.1);
  }
  
  &:active {
    transform: translateY(0);
    box-shadow: none;
  }
}

.brand-container {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 16px;
  background: rgba(255, 36, 66, 0.05);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    background: rgba(255, 36, 66, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 36, 66, 0.1);
  }
  
  .logo-animation {
    width: 40px;
    height: 40px;
    position: relative;
    overflow: hidden;
    border-radius: 8px;
    background: linear-gradient(135deg, #ff2442 0%, #ff6b81 100%);
    box-shadow: 0 4px 8px rgba(255, 36, 66, 0.25);
  }
  
  .logo-icon {
    position: relative;
    width: 100%;
    height: 100%;
  }
  
  .logo-square {
    position: absolute;
    width: 16px;
    height: 16px;
    background: white;
    top: 6px;
    left: 6px;
    border-radius: 3px;
  }
  
  .logo-circle {
    position: absolute;
    width: 10px;
    height: 10px;
    background: white;
    bottom: 8px;
    right: 8px;
    border-radius: 50%;
  }
  
  .logo-text {
    font-family: 'PingFang SC', sans-serif;
    font-size: 24px;
    font-weight: 700;
    color: #ff2442;
    letter-spacing: 1px;
    display: flex;
    flex-direction: column;
    line-height: 1.2;
  }
  
  .logo-subtitle {
    font-size: 12px;
    font-weight: 500;
    letter-spacing: 0.5px;
    opacity: 0.8;
  }
}
</style>
